<template>
<div class="trigger">
  <div class="top">
    <el-button type="text"
               class="primary_btn"
               @click.stop="openDialog('add')"
               size="mini">
      <i class="el-icon-plus"></i>{{$t('config.business.addTrigger')}}
    </el-button>
  </div>
  <table class="el-table el-table--enable-row-hover" border="0" cellspacing="0">
    <thead>
    <tr>
      <th>
        <div class="cell">{{$t('config.business.executionOrder')}}</div>
      </th>
      <th>
        <div class="cell">{{$t('config.business.triggerHeading')}}</div>
      </th>
      <th>
        <div class="cell">{{$t('config.business.triggerDescribe')}}</div>
      </th>
      <th>
        <div class="cell">{{$t('config.business.triggerFounder')}}</div>
      </th>
      <th>
        <div class="cell">{{$t('config.business.triggerCreationTime')}}</div>
      </th>
      <th>
        <div class="cell">{{$t('config.business.triggerStatus')}}</div>
      </th>
      <th>
        <div class="cell">{{$t('config.business.triggerOperation')}}</div>
      </th>
    </tr>
    </thead>
    <draggable
      :list="list"
      element="tbody"
      class="el-table__body"
      @update="sortList"
      :options="{ handle: '.field-move'}"
    >
      <tr v-for="(item, index) in draglist" :key="index">
        <td>
          <div class="cell">
            <i class="field-move iconfont icon-shunxutuozhuai"></i>
          </div>
        </td>
        <td>
          <div class="cell">
            {{item.title | interception}}
          </div>
        </td>
        <td>
          <div class="cell">
            {{item.desc | interception}}
          </div>
        </td>
        <td>
          <div class="cell">
            {{item.createName}}
          </div>
        </td>
        <td>
          <div class="cell">
            {{item.createTime}}
          </div>
        </td>
        <td>
          <div class="cell">
            {{state[item.state]}}
          </div>
        </td>
        <td>
          <div class="cell">
            <el-button type="text"
                       @click.stop="openDialog('edit', item)"
                       size="mini">
              {{$t('config.business.edit')}}
            </el-button>
            <el-popover
              placement="top"
              v-model="item.show"
              trigger="click">
              <div class="popover"><i class="flow-table__disable el-icon-warning"></i>{{$t('config.business.disableConfirm')}}</div>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" @click="changeStatus('stop', item)">{{$t('config.business.disable')}}</el-button>
                <el-button type="primary" size="mini" @click="item.show = false">{{$t('public.cancel')}}</el-button>
              </div>
              <el-button type="text"
                         class="button-waring"
                         style="margin-left: 10px"
                         slot="reference"
                         size="mini">
                {{$t('config.business.disable')}}
              </el-button>
            </el-popover>
          </div>
        </td>
      </tr>
    </draggable>
    <tbody class="el-table__body">
      <tr v-for="(item, index) in noDraglist" class="field-item">
        <td>
          <div class="cell">
            <i class="iconfont"></i>
          </div>
        </td>
        <td>
          <div class="cell">
            {{item.title | interception}}
          </div>
        </td>
        <td>
          <div class="cell">
            {{item.desc | interception}}
          </div>
        </td>
        <td>
          <div class="cell">
            {{item.createName}}
          </div>
        </td>
        <td>
          <div class="cell">
            {{item.createTime}}
          </div>
        </td>
        <td>
          <div class="cell state-stop">
            {{state[item.state]}}
          </div>
        </td>
        <td>
          <div class="cell">
            <el-button type="text"
                       @click.stop="openDialog('edit', item)"
                       size="mini">
              {{$t('config.business.edit')}}
            </el-button>
            <el-popover
              placement="top"
              v-model="item.show"
              trigger="click">
              <div class="popover"><i class="el-icon-warning"></i>{{$t('config.business.enabelConfirm')}}</div>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" @click="changeStatus('run', item)">{{$t('config.business.enabeld')}}</el-button>
                <el-button type="primary" size="mini" @click="item.show = false">{{$t('public.cancel')}}</el-button>
              </div>
              <el-button type="text"
                         slot="reference"
                         style="margin-left: 10px"
                         size="mini">
                {{$t('config.business.enabeld')}}
              </el-button>
            </el-popover>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</div>
</template>

<script>
  import draggable from 'vuedraggable'
  import rightLayout from '../base/rightLayout'
  import triggerForm from './triggerForm'
  import {cloneDeep} from 'lodash'
  import {strToArr} from '@/utils/workflowUtils'
  export default {
    name: 'flow-trigger',
    data () {
      return {
        list: [
        ],
        state: {
          run:this.$t('config.business.enabeld'),
          stop: this.$t('config.business.disable')
        }
      }
    },
    props: {
      // 当前步骤信息
      currentStepInfo: {
        type: Object,
        default: function () {
          return {}
        }
      }
    },
    filters: {
      interception (str) {
        if (str && str.length > 20) {
          return str.substring(0, 20) + '...'
        }
        return str
      }
    },
    computed: {
      draglist () {
        return this.list.filter((item) => {
          return item.state === 'run'
        })
      },
      noDraglist () {
        return this.list.filter((item) => {
          return item.state === 'stop'
        })
      },
      stepId () {
        return this.currentStepInfo._id
      }
    },
    components: {
      rightLayout,
      triggerForm,
      draggable
    },
    methods: {
      openDialog (type, data) {
        let nowdata = cloneDeep(data)
        this.$emit('openDialog', type, nowdata)
      },
      // 添加或编辑保存
      save (type, data, done) {
        console.log(data)
        if (!data) {
          return
        }
        let actions = data.actions || []
        // 如果发送短信，提醒弹框
        if (actions.some(item => item.type === 'sendSms' || item.type === 'sendSatisfaction')) {
          this.$confirm('短信消息会产生额外计费，请谨慎开启。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (type === 'add') {
              this.addTrigger(data, done)
            } else {
              this.updataTrigger(data, done)
            }
          })
        } else {
          if (type === 'add') {
            this.addTrigger(data, done)
          } else {
            this.updataTrigger(data, done)
          }
        }
      },
      addTrigger (form, done) {
        let data = cloneDeep(form)
        data.stepId = this.stepId
        data.flow_id = this.currentStepInfo.flow_id
        data.actions.forEach((item) => {
          if (item.type === 'sendMail') {
            item.customCc = strToArr(item.customCc)
            item.customTo = strToArr(item.customTo)
          }
        })
        return this.$store.dispatch('addBusinessTrigger', data).then((res) => {
          if (res.success) {
            this.$message.success('添加成功')
            done && done()
            this.search()
          }
        })
      },
      updataTrigger (form, done) {
        let data = cloneDeep(form)
        data.stepId = this.stepId
        data.flow_id = this.currentStepInfo.flow_id
        data.actions.forEach((item) => {
          if (item.type === 'sendMail') {
            item.customCc = strToArr(item.customCc)
            item.customTo = strToArr(item.customTo)
          }
        })
        return this.$store.dispatch('updateBusinessTrigger', data).then((res) => {
          if (res.success) {
            this.$message.success('更新成功')
            done && done()
            this.search()
          }
        })
      },
      search () {
        this.$store.dispatch('queryBusinessTrigger', {stepId: this.stepId}).then((res) => {
          if (res.success) {
            this.list = (res.triggers || []).map((item) => {
              let agent = this.$agentsMap() || {}
              item.createName = agent[item.createUser] ? `${agent[item.createUser].displayName}[${agent[item.createUser].exten}]` : ''
              item.show = false
              return item
            })
          }
        })
      },
      // 排序请求
      sortList () {
        let sortList = this.list.map((item) => {
          return item.triggerId
        })
        this.$store.dispatch('controlBusinessTrigger', {flow_id: this.currentStepInfo.flow_id, stepId: this.stepId, actionType: 'sort', sortList}).then((res) => {
          if (res.success) {
            this.$message.success('排序成功')
          }
        })
      },
      // 启用停用
      changeStatus (status, item) {
        this.$store.dispatch('controlBusinessTrigger', {flow_id: this.currentStepInfo.flow_id, triggerId: item.triggerId, stepId: this.stepId, actionType: status}).then((res) => {
          if (res.success) {
            this.search()
          }
        })
      },
      initData () {
        this.search()
        // 获取最新客户字段
        this.$store.dispatch('getCustomerTemplate', {account: this.$store.state.session.user.account}).then((res) => {
          if (res.success) {
            this.$updateCache('custTmpls', res.data)
          }
        })
        // this.$store.dispatch('getCache', { type: 'smsTemplate', loadFromServer: true })
      }
    }
  }
</script>

<style scoped lang='stylus'>
  @import '../../../../../assets/common.styl'
  .trigger
    .top
      border 1px solid $c-border2
      border-bottom none
      padding 5px 0
    .flow-table__button
      color $c-main
      display inline-block
      padding-right:10px
      cursor pointer
    .field-move
      cursor pointer
    .button-waring
      color $c-pink
    .state-stop
      color $cf-color0
  .popover
    font-size 12px
    padding-bottom 15px
    i
      color $cf-color0
      font-size 16px
      margin-right 5px
</style>
